//
//  RecordMainCell.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/8.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import YYText


class RecordMainCell: UITableViewCell {
    var entryCover: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.mg_blue.withAlphaComponent(0.3)
        view.layer.cornerRadius = 50
        
        return view
    }()
    
    var entryButton: UIButton = {
        let button = UIButton()
        
        button.backgroundColor = UIColor.mg_blue
        button.titleLabel?.numberOfLines = 2
        button.titleLabel?.textAlignment = .center
        button.layer.cornerRadius = 45
        button.layer.masksToBounds = true
        
        return button
    }()
    
    
    var exitCover: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.mg_blue.withAlphaComponent(0.3)
        view.layer.cornerRadius = 50
        
        return view
    }()
    var exitButton: UIButton = {
        let button = UIButton()
        
        button.backgroundColor = colorWith255RGB(247, g: 153, b: 146)
        button.titleLabel?.numberOfLines = 2
        button.titleLabel?.textAlignment = .center
        button.layer.cornerRadius = 45
        button.layer.masksToBounds = true
        
        return button
    }()
    
    //cell下方的提示label
    var checkLocationLabel: YYLabel = {
        let label = YYLabel()
        
        let attributedText = NSMutableAttributedString(string: "当前不在签到范围内")
        
        
        let imageView = UIImageView(image: UIImage.init(named: "警告"))
        imageView.frame = CGRect(x: 0, y: 0, width: 15, height: 15)
        let attributedImage = NSAttributedString.yy_attachmentString(withContent: imageView, contentMode: .scaleAspectFit, attachmentSize: CGSize.init(width: 15, height: 15), alignTo: wwFont_Regular(12), alignment: .bottom)
        attributedText.insert(attributedImage, at: 0)
        
//        let clickText = NSMutableAttributedString(string: "查看签到范围")
//        clickText.yy_font = wwFont_Regular(12)
//        clickText.yy_setTextHighlight(NSRange.init(location: 0, length: clickText.length), color: colorWith255RGB(16, g: 142, b: 233), backgroundColor: UIColor.lightGray){ (_, _, _, _) in
//        }
        
//        attributedText.append(clickText)
        
        label.attributedText = attributedText
        return label
    }()
    
    var _entryTime: String!
    var entryTime: String {
        set {
            let tempString = buttonContent("进场", time: newValue)
            self.entryButton.setAttributedTitle(tempString, for: .normal)
        }
        get {
            if _entryTime != nil {
                return _entryTime
            }
            return "00:00:00"
            
        }
    }
    
    var _exitTime: String!
    var exitTime: String {
        set {
            let tempString = buttonContent("离场", time: newValue)
            self.exitButton.setAttributedTitle(tempString, for: .normal)
        }
        get {
            if _entryTime != nil {
                return _entryTime
            }
            return  "00:00:00"
        }
    }
    
    var noData = false {
        willSet {
            self.noData = newValue
            self.updateViews()
        }
    }
    
    var entryButtonEnable = false {
        willSet {
            self.entryButton.isEnabled = newValue
            if newValue {
                self.entryButton.isEnabled = true
                self.entryCover.backgroundColor = UIColor.mg_blue.withAlphaComponent(0.3)
                self.entryButton.backgroundColor = UIColor.mg_blue
            }
            else {
                self.entryTime = "00:00:00"
                self.entryButton.backgroundColor = UIColor.mg_noDataGray
                self.entryCover.backgroundColor = UIColor.mg_noDataGray.withAlphaComponent(0.3)
                self.entryButton.isEnabled = false
            }
        }
    }
    
    var exitButtonEnable = false {
        willSet {
            self.exitButton.isEnabled = newValue
            if newValue {
                self.exitButton.backgroundColor = colorWith255RGB(247, g: 153, b: 146)
                self.exitCover.backgroundColor = colorWith255RGB(247, g: 153, b: 146).withAlphaComponent(0.3)
                self.exitButton.isEnabled = true
            }
            else {
                self.exitTime = "00:00:00"
                self.exitButton.backgroundColor = UIColor.mg_noDataGray
                self.exitCover.backgroundColor = UIColor.mg_noDataGray.withAlphaComponent(0.3)
                self.exitButton.isEnabled = false
            }
        }
    }
    
    //是否在签到范围
    var inRange = true {
        willSet {
            self.checkLocationLabel.isHidden = newValue
        }
    }
    
    
    //签入签出按钮触发控制器
    var entryButtonTouchHandler:(() -> Void)?
    var exitButtonTouchHandler:(() -> Void)?

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        
        self.entryButton.addTarget(self, action: #selector(doEntryButtonAction), for: .touchUpInside)
        self.exitButton.addTarget(self, action: #selector(doExitButtonAction), for: .touchUpInside)
        
        self.setupViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupViews() {
        self.contentView.addSubview(self.entryCover)
        self.entryCover.snp.makeConstraints { (make) in
            make.top.equalTo(self.contentView).offset(10)
            make.centerX.equalTo(self.contentView)
            make.width.height.equalTo(100)
        }
        
        self.entryCover.addSubview(entryButton)
        self.entryButton.snp.makeConstraints { (make) in
            make.center.equalTo(self.entryCover)
            make.width.height.equalTo(90)
        }
        
        self.contentView.addSubview(self.exitCover)
        self.exitCover.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.entryButton)
            make.top.equalTo(self.entryCover.snp.bottom).offset(20)
            make.size.equalTo(self.entryCover)
        }
        
        self.exitCover.addSubview(exitButton)
        self.exitButton.snp.makeConstraints { (make) in
            make.center.equalTo(self.exitCover)
            make.width.height.equalTo(90)
        }
        
        self.checkLocationLabel.isHidden = true
        self.contentView.addSubview(checkLocationLabel)
        self.checkLocationLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.contentView)
            make.bottom.equalTo(self.contentView).offset(-10)
        }
    }

    func updateViews() {
        if self.noData {
            self.entryTime = "00:00:00"
            self.entryButton.backgroundColor = UIColor.mg_noDataGray
            self.entryCover.backgroundColor = UIColor.mg_noDataGray.withAlphaComponent(0.3)
            self.entryButton.isEnabled = false
            self.checkLocationLabel.isHidden = true
            self.exitTime = "00:00:00"
            self.exitButton.backgroundColor = UIColor.mg_noDataGray
            self.exitCover.backgroundColor = UIColor.mg_noDataGray.withAlphaComponent(0.3)
            self.exitButton.isEnabled = false
            
            self.stopTimer()
        }
        else {
            self.entryButton.backgroundColor = UIColor.mg_blue
            self.entryCover.backgroundColor = UIColor.mg_blue.withAlphaComponent(0.3)
            self.entryButton.isEnabled = true
            self.exitButton.backgroundColor = colorWith255RGB(247, g: 153, b: 146)
            self.exitCover.backgroundColor = colorWith255RGB(247, g: 153, b: 146).withAlphaComponent(0.3)
            self.exitButton.isEnabled = true
            self.checkLocationLabel.isHidden = true
            
            self.beginTimer()
        }
        
    }

    //entryButton和exitButton的内容
    fileprivate func buttonContent(_ type: String, time: String) -> NSMutableAttributedString {
        let attributedText = NSMutableAttributedString(string: type + "\n",attributes: [NSAttributedStringKey.font:wwFont_Medium(17)])
        let timeText = NSAttributedString(string: time, attributes: [NSAttributedStringKey.font:wwFont_Medium(12)])
        attributedText.append(timeText)
        attributedText.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.white], range: NSRange.init(location: 0, length: attributedText.length))
        
        return attributedText
    }
    
    var timer:Timer?
    fileprivate func beginTimer() {
        if timer != nil {
            timer!.fireDate = Date()
            
            return
        }
        self.timer = Timer(timeInterval: 1, target: self, selector: #selector(doTimerAction), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: .commonModes)
    }
    
    fileprivate func stopTimer() {
        if self.timer != nil {
            self.timer!.fireDate = Date.distantFuture
        }
    }
    
    func doTimerAction() {
        let date = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "hh:mm:ss"
        let dateString = formatter.string(from: date)
        
        self.entryTime = dateString
        self.exitTime = dateString
    }
    
    fileprivate var isEntryAnimaiton = true
    @objc func doEntryButtonAction() {
        self.isEntryAnimaiton = true
        let scale = self.entryCover.bounds.width / self.entryButton.bounds.width
        let animaiton = AnimationTool.createRippleAnimation(scale: scale, duration: 0.5,delegate: self)
        self.entryButton.layer.add(animaiton, forKey: nil)
    }
    
    @objc func doExitButtonAction() {
        self.isEntryAnimaiton = false
        
        let scale = self.exitCover.bounds.width / self.entryButton.bounds.width
        let animaiton = AnimationTool.createRippleAnimation(scale: scale, duration: 0.5,delegate: self)
        self.exitButton.layer.add(animaiton, forKey: nil)
    }
}

extension RecordMainCell: CAAnimationDelegate {
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if flag {
            if isEntryAnimaiton {
                if let entryHandler = self.entryButtonTouchHandler {
                    self.entryButton.layer.removeAllAnimations()
                    entryHandler()
                }
            
            }
            else {
                if let exitHandler = self.exitButtonTouchHandler {
                    self.exitButton.layer.removeAllAnimations()
                    exitHandler()
                }
            }
        }
        
    }
}
